package org.zoum.codegenerator.gen;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author zoum
 */
@RequestMapping("/gen")
@Controller
public class GenController {

    @RequestMapping("/index")
    public String index() {
        return "index";
    }

    @RequestMapping("/gen1")
    @ResponseBody
    public void gen1(HttpServletResponse response) {

        Configuration configuration = new Configuration(Configuration.VERSION_2_3_30);
        configuration.setDefaultEncoding(StandardCharsets.UTF_8.name());
        configuration.setClassForTemplateLoading(Object.class, "/ftl/fol/");
        try {
            // 获取模板
            Template template = configuration.getTemplate("model.ftl");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + URLEncoder.encode("a.txt", StandardCharsets.UTF_8.name()));
            // 定义输出类型
            response.setContentType("application/text");
            Writer out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));
            // 生成文件 List<Map>
            template.process(new Object(), out);

            out.flush();
            out.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
